package com.pku.smart.notity.controller;

import com.alibaba.fastjson.JSON;
import com.pku.smart.constant.PayConstant;
import com.pku.smart.log.MyLog;
import com.pku.smart.notity.service.IPayMchNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping(value = "/notity")
public class AliPayNotifyController {
    private static final MyLog _log = MyLog.getLog(AliPayNotifyController.class);

    @Autowired
    IPayMchNotifyService payMchNotifyService;

    @RequestMapping("/alipay/{mchId}/pay.action")
    public String notityPay(@PathVariable("mchId")String mchId, HttpServletRequest request) {
        _log.info("====== 开始接收支付宝支付回调通知 ======");
        _log.info("打印商户号：{}", mchId);
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        _log.info("获取支付宝POST过来反馈信息");
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        _log.info("通知请求数据:{}", JSON.toJSONString(params));
        if (params.isEmpty()) {
            _log.error("请求参数为空");
            return PayConstant.TRADE_STATUS_FAILED;
        }
        return payMchNotifyService.handleAliPayNotify(mchId, params);
    }

    @RequestMapping("/alipay/{mchId}/refund.action")
    public String notityRefund(@PathVariable("mchId")String mchId, HttpServletRequest request){
        System.out.println(mchId);
        return mchId;
    }

}
